Page({
  data: {
    parrot: {
      breed: '',
      ringNumber: '',
      hairCount: '',
      gender: '',
      birthDate: '',
      mainImage: '',
      images: [],
      videos: [],
      description: '',
      isPublished: true,
      remark: '',
      sortOrder: 0
    },
    // 临时文件
    tempMainImage: null,
    tempImages: [],
    tempVideos: [],
    // 待删除文件
    deletedImages: [],
    deletedVideos: [],
    // 评论相关
    comments: [], // 所有评论列表
    editingComment: null, // 当前正在编辑的评论
    deletedComments: [], // 待删除的评论ID
    deletedCommentImages: [] // 待删除的评论图片
  },

  onLoad(options) {
    if (options.id) {
      this.getParrotDetail(options.id)
    }
  },

  // 获取鹦鹉详情
  async getParrotDetail(id) {
    wx.showLoading({ title: '加载中' })
    try {
      const res = await wx.cloud.database()
        .collection('lalayingwu')
        .doc(id)
        .get()
      this.setData({
        parrot: res.data
      })
      
      // 加载该鹦鹉的所有评论
      await this.loadComments(id)
    } catch (err) {
      console.error('获取详情失败:', err)
      wx.showToast({ title: '加载失败', icon: 'none' })
    }
    wx.hideLoading()
  },
  
  // 加载评论
  async loadComments(parrotId) {
    try {
      const res = await wx.cloud.database()
        .collection('comments')
        .where({
          parrotId: parrotId
        })
        .orderBy('createTime', 'desc')
        .get()
      
      this.setData({
        comments: res.data.map(comment => ({
          ...comment,
          isEditing: false, // 编辑状态
          originalContent: comment.content, // 原始内容备份
          originalImages: [...comment.images], // 原始图片备份
          formattedTime: this.formatTime(comment.createTime), // 格式化时间
          isMainComment: !comment.rootComment // 主评论标识：rootComment为null表示主评论
        }))
      })
    } catch (err) {
      console.error('加载评论失败:', err)
      wx.showToast({ title: '评论加载失败', icon: 'none' })
    }
  },

  // 选择主图
  async chooseMainImage() {
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed']
      })
      this.setData({
        tempMainImage: res.tempFiles[0].tempFilePath
      })
    } catch (err) {
      console.error('选择图片失败:', err)
      wx.showToast({ title: '选择图片失败', icon: 'none' })
    }
  },

  // 选择图片
  async chooseImages() {
    try {
      const res = await wx.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sizeType: ['compressed']
      })
      this.setData({
        tempImages: [...this.data.tempImages, ...res.tempFiles.map(f => f.tempFilePath)]
      })
    } catch (err) {
      console.error('选择图片失败:', err)
      wx.showToast({ title: '选择图片失败', icon: 'none' })
    }
  },

  // 标记删除图片
  markDeleteImage(e) {
    const index = e.currentTarget.dataset.index
    const fileID = this.data.parrot.images[index]
    
    this.setData({
      deletedImages: [...this.data.deletedImages, fileID],
      'parrot.images': this.data.parrot.images.filter((_,i) => i !== index)
    })
  },
  
  // 删除临时图片
  deleteTempImage(e) {
    const index = e.currentTarget.dataset.index
    const tempImages = [...this.data.tempImages]
    tempImages.splice(index, 1)
    this.setData({ tempImages })
  },

  // 性别选择变化
  onGenderChange(e) {
    this.setData({
      'parrot.gender': e.detail.value
    })
  },

  // 出生日期选择变化
  onBirthDateChange(e) {
    this.setData({
      'parrot.birthDate': e.detail.value
    })
  },

  // 选择视频
  async chooseVideos() {
    try {
      const res = await wx.chooseMedia({
        count: 3,
        mediaType: ['video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30
      })
      this.setData({
        tempVideos: [...this.data.tempVideos, ...res.tempFiles.map(f => f.tempFilePath)]
      })
    } catch (err) {
      console.error('选择视频失败:', err)
      wx.showToast({ title: '选择视频失败', icon: 'none' })
    }
  },

  // 标记删除视频
  markDeleteVideo(e) {
    const index = e.currentTarget.dataset.index
    const fileID = this.data.parrot.videos[index]
    
    this.setData({
      deletedVideos: [...this.data.deletedVideos, fileID],
      'parrot.videos': this.data.parrot.videos.filter((_,i) => i !== index)
    })
  },
  
  // 删除临时视频
  deleteTempVideo(e) {
    const index = e.currentTarget.dataset.index
    const tempVideos = [...this.data.tempVideos]
    tempVideos.splice(index, 1)
    this.setData({ tempVideos })
  },
  
  // 评论管理相关方法
  
  // 开始编辑评论
  startEditComment(e) {
    const index = e.currentTarget.dataset.index
    const comments = this.data.comments.map((comment, i) => ({
      ...comment,
      isEditing: i === index
    }))
    this.setData({ comments })
  },
  
  // 取消编辑评论
  cancelEditComment(e) {
    const index = e.currentTarget.dataset.index
    const comments = [...this.data.comments]
    comments[index] = {
      ...comments[index],
      isEditing: false,
      content: comments[index].originalContent,
      images: [...comments[index].originalImages]
    }
    this.setData({ comments })
  },
  
  // 评论内容输入
  onCommentInput(e) {
    const commentId = e.currentTarget.dataset.id
    const value = e.detail.value
    const index = this.data.comments.findIndex(c => c._id === commentId)
    const comments = [...this.data.comments]
    comments[index].content = value
    this.setData({ comments })
  },
  
  // 删除评论图片
  deleteCommentImage(e) {
    const commentIndex = e.currentTarget.dataset.commentIndex
    const imageIndex = e.currentTarget.dataset.imageIndex
    const comments = [...this.data.comments]
    const imageUrl = comments[commentIndex].images[imageIndex]
    
    // 添加到待删除列表
    this.setData({
      deletedCommentImages: [...this.data.deletedCommentImages, imageUrl]
    })
    
    // 从评论中移除图片
    comments[commentIndex].images.splice(imageIndex, 1)
    this.setData({ comments })
  },
  
  // 保存评论修改
  async saveComment(e) {
    const index = e.currentTarget.dataset.index
    const comment = this.data.comments[index]
    
    wx.showLoading({ title: '保存中' })
    try {
      // 先删除标记为待删除的评论图片
      if (this.data.deletedCommentImages.length > 0) {
        const deleteResult = await wx.cloud.callFunction({
          name: 'quickstartFunctions',
          data: {
            type: 'deleteCommentImage',
            imageUrls: this.data.deletedCommentImages
          }
        })
        
        if (!deleteResult.result.success) {
          throw new Error(deleteResult.result.error || '删除图片失败')
        }
        // 清空待删除列表
        this.setData({ deletedCommentImages: [] })
      }
      
      // 再更新评论内容
      const updateResult = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'updateComment',
          commentId: comment._id,
          content: comment.content,
          images: comment.images
        }
      })
      
      if (!updateResult.result.success) {
        throw new Error(updateResult.result.error || '更新评论失败')
      }
      
      // 更新本地状态
      const comments = [...this.data.comments]
      comments[index] = {
        ...comments[index],
        isEditing: false,
        originalContent: comment.content,
        originalImages: [...comment.images]
      }
      this.setData({ comments })
      
      wx.showToast({ title: '评论保存成功' })
    } catch (err) {
      console.error('保存评论失败:', err)
      wx.showToast({ title: '保存失败', icon: 'none' })
    } finally {
      wx.hideLoading()
    }
  },
  
  // 删除评论
  async deleteComment(e) {
    const commentId = e.currentTarget.dataset.id
    const index = this.data.comments.findIndex(c => c._id === commentId)
    const comment = this.data.comments[index]
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中' })
          try {
            // 调用云函数删除评论
            const result = await wx.cloud.callFunction({
              name: 'quickstartFunctions',
              data: {
                type: 'deleteSingleComment',
                commentId: comment._id
              }
            })
            
            if (result.result.success) {
              // 更新本地数据
              const comments = [...this.data.comments]
              comments.splice(index, 1)
              this.setData({ comments })
              wx.showToast({ title: '评论删除成功' })
            } else {
              wx.showToast({ 
                title: result.result.error || '删除失败', 
                icon: 'none',
                duration: 3000
              })
            }
          } catch (err) {
            console.error('删除评论失败:', err)
            wx.showToast({ 
              title: err.errMsg || '删除失败', 
              icon: 'none',
              duration: 3000
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 保存鹦鹉信息
  async saveParrot(e) {
    const formData = e.detail.value
    const { parrot, tempMainImage, tempImages, tempVideos, deletedImages, deletedVideos } = this.data

    // 表单验证
    if (!parrot.mainImage && !tempMainImage) {
      return wx.showToast({ title: '请上传主图', icon: 'none' })
    }
    if (!formData.breed || !formData.breed.trim()) {
      return wx.showToast({ title: '请输入品种', icon: 'none' })
    }
    if (!formData.ringNumber || !formData.ringNumber.trim()) {
      return wx.showToast({ title: '请输入脚环号', icon: 'none' })
    }

    wx.showLoading({ title: '处理中' })
    try {
      // 上传所有临时文件
      const uploadTasks = []
      
      // 上传主图
      if (tempMainImage) {
        uploadTasks.push(
          wx.cloud.uploadFile({
            cloudPath: `yingwu/main/${Date.now()}`,
            filePath: tempMainImage
          })
        )
        // 如果替换主图，将原主图加入待删除
        if (parrot.mainImage) {
          deletedImages.push(parrot.mainImage)
        }
      }
      
      // 上传图片
      tempImages.forEach(path => {
        uploadTasks.push(
          wx.cloud.uploadFile({
            cloudPath: `yingwu/images/${Date.now()}-${Math.random()}`,
            filePath: path
          })
        )
      })
      
      // 上传视频
      tempVideos.forEach(path => {
        uploadTasks.push(
          wx.cloud.uploadFile({
            cloudPath: `yingwu/videos/${Date.now()}-${Math.random()}.mp4`,
            filePath: path
          })
        )
      })
      
      // 执行所有上传
      const results = await Promise.all(uploadTasks)
      
      // 删除标记文件
      if (deletedImages.length > 0 || deletedVideos.length > 0) {
        await wx.cloud.deleteFile({
          fileList: [...deletedImages, ...deletedVideos]
        })
      }
      
      // 准备数据库数据
      const db = wx.cloud.database()
      const updateData = {
        breed: formData.breed,
        ringNumber: formData.ringNumber,
        hairCount: formData.hairCount,
        gender: ['公','母','未知'].indexOf(formData.gender) >= 0 ? 
          ['公','母','未知'][['公','母','未知'].indexOf(formData.gender)] : formData.gender,
        birthDate: formData.birthDate,
        mainImage: tempMainImage ? results.shift().fileID : parrot.mainImage,
        images: [
          ...parrot.images,
          ...results.slice(0, tempImages.length).map(r => r.fileID)
        ],
        videos: [
          ...(parrot.videos || []),
          ...results.slice(tempImages.length).map(r => r.fileID)
        ],
        description: formData.description,
        isPublished: formData.isPublished,
        remark: formData.remark,
        sortOrder: formData.sortOrder || 0,
        updateTime: db.serverDate()
      }
      
      // 保存到数据库
      if (parrot._id) {
        await db.collection('lalayingwu')
          .doc(parrot._id)
          .update({ data: updateData })
      } else {
        await db.collection('lalayingwu')
          .add({ data: updateData })
      }
      
      wx.showToast({ title: '保存成功' })
      setTimeout(() => wx.navigateBack(), 1500)
    } catch (err) {
      console.error('保存失败:', err)
      wx.showToast({ 
        title: `保存失败: ${err.errMsg || err.message}`,
        icon: 'none',
        duration: 3000
      })
    } finally {
      wx.hideLoading()
    }
  },
  
  // 时间格式化函数
  formatTime(time) {
    if (!time) return ''
    
    const date = new Date(time)
    const now = new Date()
    const diff = now - date
    
    // 一分钟内
    if (diff < 60000) {
      return '刚刚'
    }
    
    // 一小时内
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前'
    }
    
    // 一天内
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前'
    }
    
    // 一年内
    if (diff < 31536000000) {
      return Math.floor(diff / 86400000) + '天前'
    }
    
    // 超过一年
    return date.getFullYear() + '年' + 
           (date.getMonth() + 1) + '月' + 
           date.getDate() + '日 ' + 
           date.getHours().toString().padStart(2, '0') + ':' + 
           date.getMinutes().toString().padStart(2, '0')
  }
})
